package com.example.rediscacheproject.service.impl.UserServiceImpl;

import com.example.rediscacheproject.entity.User;
import com.example.rediscacheproject.mapper.UserMapper;
import com.example.rediscacheproject.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    /**
     * 根据ID获取用户（带缓存）
     * 缓存名称：cachedemo
     * 缓存key：用户ID
     */
    @Override
    @Cacheable(value = "cachedemo", key = "#id")
    public User getUserById(Long id) {
        log.info("从数据库查询用户数据，ID: {}", id);
        User user = getById(id);
        if (user != null) {
            log.info("用户数据查询成功并已缓存，ID: {}", id);
        } else {
            log.info("用户不存在，ID: {}", id);
        }
        return user;
    }

    /**
     * 获取所有用户（带缓存）
     * 缓存名称：cachedemo
     * 缓存key：固定字符串 "list"
     */
    @Override
    @Cacheable(value = "cachedemo", key = "'list'")
    public List<User> getAllUsers() {
        log.info("从数据库查询用户列表数据");
        List<User> users = list();
        log.info("用户列表数据查询成功并已缓存，共{}条记录", users != null ? users.size() : 0);
        return users;
    }

    /**
     * 创建用户
     * 创建成功后删除列表缓存
     */
    @Override
    @CacheEvict(value = "cachedemo", key = "'list'")
    public boolean createUser(User user) {
        log.info("开始创建用户：{}", user.getName());
        boolean result = save(user);
        if (result) {
            log.info("用户创建成功，ID: {}, 已删除列表缓存", user.getId());
        } else {
            log.error("用户创建失败");
        }
        return result;
    }

    /**
     * 更新用户（删除缓存策略）
     * 删除指定用户缓存和列表缓存
     */
    @Override
    @Caching(evict = {
            @CacheEvict(value = "cachedemo", key = "#user.id"),
            @CacheEvict(value = "cachedemo", key = "'list'")
    })
    public boolean updateUser(User user) {
        log.info("开始更新用户，ID: {}", user.getId());
        boolean result = updateById(user);
        if (result) {
            log.info("用户更新成功，ID: {}, 已删除相关缓存", user.getId());
        } else {
            log.error("用户更新失败，ID: {}", user.getId());
        }
        return result;
    }

    /**
     * 删除用户（删除缓存策略）
     * 删除指定用户缓存和列表缓存
     */
    @Override
    @Caching(evict = {
            @CacheEvict(value = "cachedemo", key = "#id"),
            @CacheEvict(value = "cachedemo", key = "'list'")
    })
    public boolean deleteUser(Long id) {
        log.info("开始删除用户，ID: {}", id);
        boolean result = removeById(id);
        if (result) {
            log.info("用户删除成功，ID: {}, 已删除相关缓存", id);
        } else {
            log.error("用户删除失败，ID: {}", id);
        }
        return result;
    }

    /**
     * 手动清除指定用户的缓存
     */
    @CacheEvict(value = "cachedemo", key = "#id")
    public void clearUserCache(Long id) {
        log.info("手动清除用户缓存，ID: {}", id);
    }

    /**
     * 手动清除用户列表缓存
     */
    @CacheEvict(value = "cachedemo", key = "'list'")
    public void clearUserListCache() {
        log.info("手动清除用户列表缓存");
    }

    /**
     * 手动清除所有用户相关缓存
     */
    @CacheEvict(value = "cachedemo", allEntries = true)
    public void clearAllUserCache() {
        log.info("手动清除所有用户相关缓存");
    }
}
